<template>
  <!-- 新增修改用户 -->
  <BaseDrawer
    width="50%"
    :title="drawerTitle"
    placement="right"
    v-model:visible="open"
    :maskClosable="false"
    @close="handleClose"
  >
    <template #default>
      <a-form
        v-if="open"
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-row>
          <a-col :span="12" v-show="formState.deptId !== 0">
            <a-form-item :label="t('routes.user.deptId')" name="deptId">
              <treeselect
                ref="treeRef"
                class="!mt-[3px]"
                v-model:value="formState.deptId"
                :normalizer="normalizer"
                :placeholder="t('routes.user.deptIdPlaceholder')"
                :options="deptOptions"
                @select="handleTreeSelect"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.user.nickName')" name="nickName">
              <a-input
                v-model:value="formState.nickName"
                :placeholder="t('routes.user.nickNamePlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12" v-if="!isUpdate">
            <a-form-item :label="t('routes.user.userName')" name="userName">
              <a-input
                v-model:value="formState.userName"
                :placeholder="t('routes.user.userNamePlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12" v-if="!isUpdate">
            <a-form-item :label="t('routes.user.password')" name="password">
              <a-input-password
                v-model:value="formState.password"
                :placeholder="t('routes.user.passwordPlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.user.roleIds')" name="roleIds">
              <a-select
                mode="multiple"
                v-model:value="formState.roleIds"
                :placeholder="t('routes.user.roleIdsPlaceholder')"
              >
                <a-select-option v-for="item in roleOptions" :key="item.id">
                  {{ item.roleName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.user.sex')" name="sex">
              <a-radio-group
                v-model:value="formState.sex"
                :options="sexOptions"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.user.mobile')" name="mobile">
              <a-input
                v-model:value="formState.mobile"
                :placeholder="t('routes.user.mobilePlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.user.status')" name="status">
              <a-radio-group
                v-model:value="formState.status"
                :options="disableOptions"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.user.email')" name="email">
              <a-input
                v-model:value="formState.email"
                :placeholder="t('routes.user.emailPlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="t('routes.user.remark')" name="remark">
              <a-textarea
                :rows="3"
                v-model:value="formState.remark"
                :placeholder="t('routes.user.remarkPlaceholder')"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <template #footer>
      <a-button type="primary" class="mr-3" @click="handleSubmit">
        {{ t("common.okText") }}
      </a-button>
      <a-button @click="handleClose">
        {{ t("common.cancelText") }}
      </a-button>
    </template>
  </BaseDrawer>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, onMounted, nextTick } from "vue";
import {
  Row,
  Col,
  Form,
  FormItem,
  Input,
  InputPassword,
  Select,
  SelectOption,
  RadioGroup,
  Textarea,
} from "ant-design-vue";
import BaseDrawer from "@/components/BaseDrawer/index.vue";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { message as Message } from "ant-design-vue";
import { getUser, addUser, updateUser } from "@/api/admin/system/user";
import { getRole } from "@/api/admin/system/role";
import useDrawer from "@/hooks/useDrawer";
import Treeselect from "vue3-treeselect";
import "vue3-treeselect/dist/vue3-treeselect.css";
import { formRules } from "@/utils/validate";

import { IRole } from "@/api/admin/system/role/type";
import { IData } from "@/api/admin/system/dict/data/type";
import { IDept } from "@/api/admin/system/dept/type";
import { useI18n } from "@/hooks/useI18n";
import { IUser } from "@/api/admin/system/user/type";
import { getDict } from "@/utils/dictFormat";
import { getDept } from "@/api/admin/system/dept";
import { handleTree } from "@/utils/tools";
import { useUserStore } from "@/store/modules/user";

const { t } = useI18n();

interface FormState {
  id: undefined | number;
  deptId: undefined | number;
  nickName: undefined | string;
  userName: undefined | string;
  password: undefined | string;
  sex: undefined | string;
  roleIds: undefined | number[];
  mobile: undefined | number | string;
  status: undefined | string;
  email: undefined | string;
  remark: undefined | string;
}

export default defineComponent({
  components: {
    "a-row": Row,
    "a-col": Col,
    "a-form": Form,
    "a-form-item": FormItem,
    "a-input": Input,
    "a-input-password": InputPassword,
    "a-select": Select,
    "a-select-option": SelectOption,
    "a-radio-group": RadioGroup,
    "a-textarea": Textarea,
    Treeselect,
    BaseDrawer,
  },
  emits: ["finished"],
  setup(props, { expose, emit }) {
    const userStore = useUserStore();
    const roleOptions = ref<IRole[]>([]);
    const disableOptions = ref<IData[]>([]);
    const sexOptions = ref<IData[]>([]);
    // 部门树选项
    const deptOptions = ref<IDept[]>([]);

    /**
     * 推窗表单操作
     */
    // 获取部门树
    const treeRef = ref();
    const formState: FormState = reactive({
      id: undefined,
      deptId: undefined,
      nickName: undefined,
      userName: undefined,
      password: undefined,
      sex: "1",
      roleIds: undefined || [],
      mobile: undefined,
      status: "1",
      email: undefined,
      remark: undefined,
    });
    const rules = {
      deptId: [
        {
          required: true,
          validator: formRules.number,
          message: t("routes.user.deptIdCannotBeEmpty"),
          trigger: "change",
        },
      ],
      nickName: [
        {
          required: true,
          message: t("routes.user.nickNameCannotBeEmpty"),
          trigger: "blur",
        },
      ],
      userName: [
        {
          required: true,
          message: t("routes.user.userNameCannotBeEmpty"),
          trigger: "blur",
        },
      ],
      password: [
        {
          required: true,
          message: t("routes.user.passwordCannotBeEmpty"),
          trigger: "blur",
        },
      ],
      roleIds: [
        {
          required: true,
          validator: formRules.checkRoleLength,
          trigger: "change",
        },
      ],
    };

    const isUpdate = ref(false); // 是否更新操作
    // 上级部门选中事件
    const handleTreeSelect = (node) => {
      formState.deptId = node.deptId;
    };

    // 序列化部门
    const normalizer = (node) => {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    };
    const formRef = ref();
    const { open, drawerTitle, handleOpenDrawer, handleCloseDrawer } =
      useDrawer();

    // 关闭推窗
    const handleClose = (cb?: () => void) => {
      handleCloseDrawer.value(() => {
        formState.id = undefined;
        formState.deptId = undefined;
        formState.password = undefined;
        formState.userName = undefined;
        formState.roleIds = undefined;
        formRef.value.resetFields();
        cb && typeof cb === "function" && cb();
      });
    };
    // 显示推窗
    const handleShow = (row?: IUser) => {
      handleOpenDrawer.value(() => {
        if (row && row.id) {
          drawerTitle.value = t("common.update");
          getUser(row.id).then((res) => {
            isUpdate.value = true;
            nextTick(() => {
              Object.keys(formState).forEach((key) => {
                formState[key] = res.data[key];
              });
              formState.roleIds = res.data.roles.map((list) => list.id);
              treeRef.value.forest.selectedNodeIds.push(res.data.deptId);
              console.log(formState);
            });
          });
        } else {
          isUpdate.value = false;
          drawerTitle.value = t("common.add");
        }
      });
    };

    // 表单提交
    const handleSubmit = () => {
      console.log(formState);
      formRef.value
        .validate()
        .then(() => {
          if (formState.id) {
            updateUser(formState).then((res) => {
              handleClose(() => {
                Message.success(res.message);
                emit("finished");
              });
            });
          } else {
            addUser(formState).then((res) => {
              handleClose(() => {
                Message.success(res.message);
                emit("finished");
              });
            });
          }
        })
        .catch((error: ValidateErrorEntity) => {
          console.log("error", error);
        });
    };

    onMounted(async () => {
      disableOptions.value = await getDict("sys_normal_disable");
      sexOptions.value = await getDict("sys_user_sex");
      disableOptions.value.forEach((item) => {
        item.label = item.dictLabel;
        item.value = item.dictValue;
      });
      sexOptions.value.forEach((item) => {
        item.label = item.dictLabel;
        item.value = item.dictValue;
      });
      getDept().then((res) => {
        // 获取菜单树
        const children = handleTree(
          res.data.rows,
          "deptId",
          "parentId",
          "children",
          userStore.userInfo.deptId
        ).tree;
        const parent = res.data.rows.filter(
          (item) => item.deptId === userStore.userInfo.deptId
        );
        parent[0].children = children;
        deptOptions.value = parent;
        console.log(deptOptions);
      });
      getRole().then((res) => {
        roleOptions.value = res.data.rows;
      });
    });

    expose({
      handleShow,
    });

    return {
      t,
      treeRef,
      formRef,
      rules,
      isUpdate,
      open,
      drawerTitle,
      deptOptions,
      normalizer,
      handleClose,
      handleSubmit,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      formState,
      roleOptions,
      handleTreeSelect,
      disableOptions,
      sexOptions,
    };
  },
});
</script>
